<template>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="Title" prop="title" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button
          size="small"
          @click="handleAdd(scope.$index, scope.row)"
          type="primary"
          >Add</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { getCards } from "@/api/cards";
import { computed, onBeforeMount, reactive, ref, defineExpose } from "vue";
import { Card } from "../flowchart/models";
import { emitNewNode } from "@/components/EventBus";

const search = ref("");
const filterTableData = computed(() =>
  tableData.filter(
    (data) =>
      !search.value ||
      data.title.toLowerCase().includes(search.value.toLowerCase())||
      data.id.toLowerCase().includes(search.value.toLowerCase())
  )
);
const handleAdd = (index: number, row: Card) => {
  void index
  emitNewNode(row.id);
};

const tableData = reactive<Card[]>([]);

const update = async () => {
  const cards = await getCards();
  for (const i in cards) {
    tableData.push(cards[i]);
  }
};

onBeforeMount(async () => {
  await update();
});
defineExpose({ update });
</script>
